package com.peek.event;

import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.peek.util.HelpMe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Created by mengdexuan on 2017/5/18 17:59.
 */
public class DealWithStartedEvent implements ApplicationListener<ContextRefreshedEvent> {

	private static Logger log = LoggerFactory.getLogger(DealWithStartedEvent.class);
	private ActiveRecordPlugin arp = null;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
		ApplicationContext appContext = contextRefreshedEvent.getApplicationContext();

		JdbcTemplate jdbcTemplate = appContext.getBean(JdbcTemplate.class);
//		DataSourceProperties ds = appContext.getBean(DataSourceProperties.class);


		//JFinal ActiveRecordPlugin 插件配置
		//用 uuid 作为 configName,自动重启后 DbKit 不会报名称已存在的异常
		arp = new ActiveRecordPlugin(HelpMe.uuid(),jdbcTemplate.getDataSource());
		arp.start();
		close();
		log.info("项目启动完毕！");
	}

	public void close(){
		Runtime.getRuntime().addShutdownHook(new Thread(){
			public void run() {
				log.info("jvm 关闭，触发钩子函数……");
				if (arp!=null){
					arp.stop();
					arp = null;
				}
			}
		});
	}
}
